package com.soundplus.app.shp04.DeviceConnectMgr;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.util.Log;

import com.example.sppmode.Common.DataConfig;
import com.example.sppmode.DataProtocol.CommandInfo;


public class DevConnMgr {
    private static final String TAG = "DevConnMgr";
    public static final int CONN_PROTOCOL_BLE = DataConfig.CONN_PROTOCOL_TYPE_BLE;


    private static final DevConnMgr instance = new DevConnMgr();
    private DevConnService devConnService;

    private DevConnMgr() {
    }

    public static DevConnMgr getInstance() {
        return instance;
    }

    public void init(Context context) {
        if (devConnService == null) {
            Intent bindIntent = new Intent(context, DevConnService.class);
            context.bindService(bindIntent, serviceConnection, Context.BIND_AUTO_CREATE);
        }
    }

    public void destroy(Context context) {
        if (devConnService != null) {
            devConnService.disconnectDevice();
            devConnService.clearDevConnEventListener();
            devConnService = null;
            context.unbindService(serviceConnection);
        }
    }

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            Log.d(TAG, "onServiceConnected");
            devConnService = ((DevConnService.MyBinder) iBinder).getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    };

    public void addDevConnEventListener(DevConnEventListener listener) {
        if (devConnService != null) {
            devConnService.addDevConnEventListener(listener);
        }
    }

    public void removeDevConnEventListener(DevConnEventListener listener) {
        if (devConnService != null) {
            devConnService.removeDevConnEventListener(listener);
        }
    }

    public void clearDevConnEventListener() {
        if (devConnService != null) {
            devConnService.clearDevConnEventListener();
        }
    }

    public void connectDevice(int connProtocolType, String addr) {
        Log.d(TAG, "connectDevice， addr=" + addr);
        if (devConnService != null) {
            devConnService.connectDevice(connProtocolType, addr);
        }
    }

    public void disconnectDevice() {
        if (devConnService != null) {
            devConnService.disconnectDevice();
        }
    }

    public int getConnectStatus() {
        if (devConnService != null) {
            return devConnService.getDevConnectStatus();
        }

        return DataConfig.STATE_DISCONNECTED;
    }

    public void sendCommandData(CommandInfo cmdInfo) {
        if (devConnService != null) {
            devConnService.sendCommand(cmdInfo);
        }
    }


}
